<template>
  <div class="check-recheck-container">
    <!-- 搜索栏 -->
    <div class="search-bar" style="margin-bottom: 15px;margin-left: 30px;">
      <el-input v-model="searchForm.recheckNo" style="width: 240px; padding-right: 15px;" placeholder="请输入复盘单号" />
      <el-select v-model="searchForm.warehouseId" placeholder="请选择仓库" clearable style="width: 200px; margin-right: 15px;">
        <el-option v-for="warehouse in warehouseList" :key="warehouse.id" :label="warehouse.name" :value="warehouse.id" />
      </el-select>
      <el-date-picker v-model="searchForm.startDate" type="date" placeholder="开始日期" format="YYYY-MM-DD" value-format="YYYY-MM-DD" style="width: 150px; margin-right: 15px;" />
      <el-date-picker v-model="searchForm.endDate" type="date" placeholder="结束日期" format="YYYY-MM-DD" value-format="YYYY-MM-DD" style="width: 150px; margin-right: 15px;" />
      <el-icon @click="handleSearch()" style="margin-left: 20px; height: 25px; width: 25px;">
        <Search />
      </el-icon>
      <el-icon style="margin-left: 20px;" @click="resetSearch()">
        <Refresh />
      </el-icon>
      <el-button type="success" plain style="margin-left: 30px;" @click="showAddDialog()">新增复盘</el-button>
    </div>

    <!-- 复盘单表格 -->
    <el-table :data="tableData" style="width: 100%" stripe border="true" v-loading="loading">
      <el-table-column label="序号" width="80px" align="center">
        <template #default="scope">
          {{ scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column prop="recheckNo" label="复盘单号" width="180" align="center" />
      <el-table-column prop="warehouseName" label="仓库名称" width="150" align="center" />
      <el-table-column prop="recheckDate" label="复盘日期" width="150" align="center">
        <template #default="scope">{{ formatDateYMD(scope.row.recheckDate) }}</template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="120" align="center">
        <template #default="scope">
          <span v-if="scope.row.status == 0" style="color: gray;">草稿</span>
          <span v-if="scope.row.status == 1" style="color: green;">已审核</span>
          <span v-if="scope.row.status == 2" style="color: red;">已作废</span>
        </template>
      </el-table-column>
      <el-table-column prop="remark" label="备注" width="200" align="center" />
      <el-table-column label="操作" width="350px" fixed="right" align="center">
        <template #default="scope">
          <el-button type="primary" plain @click="viewRecheckDetails(scope.row.id)">详情</el-button>
          <el-button type="warning" plain @click="showEditDialog(scope.row)" v-if="scope.row.status === 0">修改</el-button>
          <el-button type="success" plain @click="onAuditRecheck(scope.row.id)" v-if="scope.row.status === 0">审核</el-button>
          <el-button type="danger" plain @click="onVoidRecheck(scope.row.id)" v-if="scope.row.status === 0">作废</el-button>
          <el-button type="danger" plain @click="onDeleteRecheck(scope.row.id)" v-if="scope.row.status === 0">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div style="position: absolute;bottom: 20px;left: 0;right: 0;height: 25px;width: 300px;margin: 0 auto; ">
      <el-pagination
        v-model:current-page="pagination.pageNum"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[3, 5, 10]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增/编辑复盘单对话框 -->
    <el-dialog v-model="dialogVisible" :title="isEdit ? '编辑复盘' : '新增复盘'" width="1150px" :before-close="handleDialogClose" :close-on-click-modal="false" style="left: 90px">
      <el-form :model="recheckForm" :rules="formRules" ref="recheckFormRef" label-width="120px" style="padding: 15px 0;">
        <el-form-item label="复盘单号" prop="recheckNo" v-if="isEdit">
          <el-input v-model="recheckForm.recheckNo" disabled placeholder="系统自动生成" />
        </el-form-item>
        <el-form-item label="仓库名称" prop="warehouseId">
          <el-select v-model="recheckForm.warehouseId" placeholder="请选择仓库" clearable style="width: 100%" @change="onWarehouseChange">
            <el-option v-for="warehouse in warehouseList" :key="warehouse.id" :label="warehouse.name" :value="warehouse.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="复盘日期" prop="recheckDate">
          <el-date-picker v-model="recheckForm.recheckDate" type="date" placeholder="请选择复盘日期" format="YYYY-MM-DD" value-format="YYYY-MM-DD" style="width: 100%" />
        </el-form-item>
        <el-form-item label="复盘状态" prop="status" v-if="isEdit">
          <el-select v-model="recheckForm.status" placeholder="请选择复盘状态" style="width: 100%">
            <el-option label="草稿" :value="0" />
            <el-option label="已审核" :value="1" />
            <el-option label="已作废" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="recheckForm.remark" type="textarea" :rows="3" placeholder="请输入备注信息" />
        </el-form-item>

        <!-- 商品明细 -->
        <el-form-item label="商品明细">
          <div class="items-container">
            <div class="items-header">
              <h4>复盘商品明细</h4>
              <el-button type="primary" size="small" @click="addProductItem">添加商品</el-button>
            </div>
            <el-table :data="recheckForm.items || []" style="width: 100%" stripe border="true" max-height="400">
              <el-table-column label="序号" width="60" align="center">
                <template #default="scope">{{ scope.$index + 1 }}</template>
              </el-table-column>
              <el-table-column label="产品名称" width="250">
                <template #default="scope">
                  <div v-if="isEdit && scope.row.productId && scope.row.productName">
                    <span>{{ scope.row.productName }}</span>
                  </div>
                  <el-select 
                    v-else
                    v-model="scope.row.productId" 
                    placeholder="选择商品" 
                    style="width: 100%"
                    @change="(productId) => onProductChange(scope.row, productId)"
                    filterable
                  >
                    <el-option 
                      v-for="product in productList" 
                      :key="product.id" 
                      :label="product.name" 
                      :value="product.id" 
                    />
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="系统数量" width="120" align="center">
                <template #default="scope">
                  {{ scope.row.systemQuantity || 0 }}
                </template>
              </el-table-column>
              <el-table-column label="实际数量" width="120" align="center">
                <template #default="scope">
                  <el-input-number 
                    v-model="scope.row.actualQuantity" 
                    :min="0" 
                    :precision="0" 
                    :step="1"
                    style="width: 100px"
                    @change="() => calculateDifference(scope.row)"
                  />
                </template>
              </el-table-column>
              <el-table-column label="差异数量" width="120" align="center">
                <template #default="scope">
                  <span :style="{ color: getDifferenceColor(scope.row.difference) }">
                    {{ scope.row.difference || 0 }}
                  </span>
                </template>
              </el-table-column>
              <el-table-column label="备注" width="150" align="center">
                <template #default="scope">
                  <el-input v-model="scope.row.remark" placeholder="备注" size="small" />
                </template>
              </el-table-column>
              <el-table-column label="操作" width="100" align="center">
                <template #default="scope">
                  <el-button type="danger" size="small" @click="removeProductItem(scope.$index)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleDialogClose" size="default">取消</el-button>
          <el-button type="primary" @click="submitForm" size="default">确认{{ isEdit ? '修改' : '创建' }}</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 复盘详情对话框 -->
    <el-dialog v-model="detailDialogVisible" title="复盘详情" width="800px" :before-close="handleDetailDialogClose" :close-on-click-modal="false">
      <div v-if="currentRecheck && Object.keys(currentRecheck).length > 0" class="recheck-detail">
        <div class="detail-header">
          <p><span class="label">复盘单号：</span>{{ currentRecheck.recheckNo }}</p>
          <p><span class="label">仓库名称：</span>{{ currentRecheck.warehouseName }}</p>
          <p><span class="label">复盘日期：</span>{{ formatDateYMD(currentRecheck.recheckDate) }}</p>
          <p><span class="label">复盘状态：</span>
            <span v-if="currentRecheck.status == 0" style="color: gray;">草稿</span>
            <span v-if="currentRecheck.status == 1" style="color: green;">已审核</span>
            <span v-if="currentRecheck.status == 2" style="color: red;">已作废</span>
          </p>
          <p><span class="label">备注：</span>{{ currentRecheck.remark || '-' }}</p>
        </div>

        <div class="detail-items">
          <h3>商品明细</h3>
          <el-table :data="(currentRecheck.items && Array.isArray(currentRecheck.items)) ? currentRecheck.items : []" style="width: 100%" stripe border="true">
            <el-table-column label="序号" width="80" align="center">
              <template #default="scope">{{ scope.$index + 1 }}</template>
            </el-table-column>
            <el-table-column label="产品名称" width="250" align="center">
              <template #default="scope">
                {{ scope.row.productName || '-' }}
              </template>
            </el-table-column>
            <el-table-column label="系统数量" width="140" align="center">
              <template #default="scope">
                {{ scope.row.systemQuantity || scope.row.quantity || 0 }}
              </template>
            </el-table-column>
            <el-table-column label="实际数量" width="140" align="center">
              <template #default="scope">
                {{ scope.row.actualQuantity || 0 }}
              </template>
            </el-table-column>
            <el-table-column label="差异数量" width="140" align="center">
              <template #default="scope">
                <span :style="{ color: getDifferenceColor(scope.row.difference) }">
                  {{ scope.row.difference || 0 }}
                </span>
              </template>
            </el-table-column>
            <el-table-column label="备注" width="150" align="center">
              <template #default="scope">
                {{ scope.row.remark || '-' }}
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleDetailDialogClose" size="default">关闭</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 审核确认对话框 -->
    <el-dialog
      v-model="auditDialogVisible"
      title="审核确认"
      width="400px"
      :close-on-click-modal="false"
    >
      <p>确定要审核通过这个复盘单吗？审核后将无法修改。</p>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="auditDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmAudit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 作废确认对话框 -->
    <el-dialog
      v-model="voidDialogVisible"
      title="作废确认"
      width="400px"
      :close-on-click-modal="false"
    >
      <p>确定要作废这个复盘单吗？作废后将无法恢复。</p>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="voidDialogVisible = false">取消</el-button>
          <el-button type="danger" @click="confirmVoid">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh } from '@element-plus/icons-vue'
import { getWarehouseList, getProductList } from '@/api/warehouse/warehouse'
import { 
  getInventoryRecheckPage, 
  getInventoryRecheckWithDetails, 
  createInventoryRecheck, 
  updateInventoryRecheck, 
  deleteInventoryRecheck, 
  auditInventoryRecheck, 
  voidInventoryRecheck,
  getProductStockQuantity
} from '@/api/check/recheck'

export default {
  name: 'CheckRecheck',
  setup() {
    // 工具函数：日期格式化仅显示 YYYY-MM-DD
    function formatDateYMD(value) {
      if (!value) return ''
      if (typeof value === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(value)) return value
      if (typeof value === 'string') {
        const m = value.match(/^(\d{4}-\d{2}-\d{2})/)
        if (m) return m[1]
      }
      try {
        const d = new Date(value)
        if (!isNaN(d.getTime())) {
          const y = d.getFullYear()
          const mm = String(d.getMonth() + 1).padStart(2, '0')
          const dd = String(d.getDate()).padStart(2, '0')
          return `${y}-${mm}-${dd}`
        }
      } catch (_) {}
      return String(value)
    }

    // 响应式数据
    const loading = ref(false)
    const dialogVisible = ref(false)
    const detailDialogVisible = ref(false)
    const auditDialogVisible = ref(false)
    const voidDialogVisible = ref(false)
    const isEdit = ref(false)
    const dialogTitle = ref('')
    const currentRecheck = ref({})
    const currentRecheckId = ref(null)

    // 搜索表单
    const searchForm = reactive({
      recheckNo: '',
      warehouseId: null,
      startDate: '',
      endDate: ''
    })

    // 分页
    const pagination = reactive({
      pageNum: 1,
      pageSize: 10,
      total: 0
    })

    // 列表数据
    const tableData = ref([])
    const warehouseList = ref([])
    const productList = ref([])

    // 复盘表单
    const recheckForm = reactive({
      id: null,
      recheckNo: '',
      warehouseId: null,
      recheckDate: '',
      remark: '',
      items: [],
      status: 0
    })

    // 表单验证规则
    const formRules = {
      warehouseId: [{ required: true, message: '请选择仓库', trigger: 'change' }],
      recheckDate: [{ required: true, message: '请选择复盘日期', trigger: 'change' }]
    }

    const loadWarehouseList = async () => {
      try {
        const data = await getWarehouseList()
        warehouseList.value = Array.isArray(data) ? data : (Array.isArray(data?.records) ? data.records : [])
      } catch (error) {
        console.error('加载仓库列表失败:', error)
      }
    }

    const loadProductList = async () => {
      try {
        const data = await getProductList()
        productList.value = Array.isArray(data) ? data : (Array.isArray(data?.records) ? data.records : [])
      } catch (error) {
        console.error('加载商品列表失败:', error)
      }
    }

    const handleSearch = () => {
      pagination.pageNum = 1
      loadData()
    }

    const resetSearch = () => {
      Object.assign(searchForm, { recheckNo: '', warehouseId: null, startDate: '', endDate: '' })
      pagination.pageNum = 1
      loadData()
    }

    const handleSizeChange = (val) => {
      pagination.pageSize = val
      loadData()
    }

    const handleCurrentChange = (val) => {
      pagination.pageNum = val
      loadData()
    }

    const showAddDialog = () => {
      isEdit.value = false
      dialogTitle.value = '新增复盘单'
      resetRecheckForm()
      dialogVisible.value = true
    }

    const showEditDialog = (row) => {
      isEdit.value = true
      dialogTitle.value = '编辑复盘单'
      Object.assign(recheckForm, row)
      if (row.items) {
        recheckForm.items = row.items.map(item => ({
          ...item,
          remark: item.remark || ''
        }))
      }
      dialogVisible.value = true
    }

    const viewRecheckDetails = async (id) => {
      try {
        const data = await getInventoryRecheckWithDetails(id)
        console.log('获取到的复盘单详情:', data)
        
        if (data && Array.isArray(data.items)) {
          data.items = data.items.map(it => {
            if (!it) return null // 防止空对象
            
            // 确保系统数量字段存在
            const systemQty = Number(it.systemQuantity || it.quantity || 0)
            const actualQty = Number(it.actualQuantity || 0)
            const difference = Math.round(actualQty - systemQty)
            
            console.log('商品明细处理:', {
              productName: it.productName,
              systemQuantity: systemQty,
              actualQuantity: actualQty,
              difference: difference
            })
            
            return {
              ...it,
              systemQuantity: systemQty,
              actualQuantity: actualQty,
              difference: difference
            }
          }).filter(Boolean) // 过滤掉null值
        }
        
        currentRecheck.value = data || {}
        detailDialogVisible.value = true
      } catch (error) {
        console.error('获取复盘单详情失败:', error)
        ElMessage.error('获取复盘单详情失败')
        currentRecheck.value = {}
      }
    }

    const onAuditRecheck = (id) => {
      currentRecheckId.value = id
      auditDialogVisible.value = true
    }

    const onVoidRecheck = (id) => {
      currentRecheckId.value = id
      voidDialogVisible.value = true
    }

    const onDeleteRecheck = async (id) => {
      try {
        await ElMessageBox.confirm('确定要删除这个复盘单吗？', '删除确认', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        await deleteInventoryRecheck(id)
        ElMessage.success('删除成功')
        loadData()
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除复盘单失败:', error)
          ElMessage.error('删除失败')
        }
      }
    }

    const confirmAudit = async () => {
      try {
        await auditInventoryRecheck(currentRecheckId.value)
        ElMessage.success('审核成功')
        auditDialogVisible.value = false
        loadData()
      } catch (error) {
        console.error('审核失败:', error)
        ElMessage.error('审核失败')
      }
    }

    const confirmVoid = async () => {
      try {
        await voidInventoryRecheck(currentRecheckId.value)
        ElMessage.success('作废成功')
        voidDialogVisible.value = false
        loadData()
      } catch (error) {
        console.error('作废失败:', error)
        ElMessage.error('作废失败')
      }
    }

    const addProductItem = () => {
      if (!Array.isArray(recheckForm.items)) {
        recheckForm.items = []
      }
      
      recheckForm.items.push({
        productId: null,
        productName: '',
        productCode: '',
        systemQuantity: 0,
        actualQuantity: 0,
        difference: 0,
        remark: ''
      })
      console.log('添加商品明细:', recheckForm.items)
    }

    const removeProductItem = (index) => {
      recheckForm.items.splice(index, 1)
    }

    const onProductChange = async (item, productId) => {
      if (productId) {
        const product = productList.value.find(p => p.id === productId)
        if (product) {
          item.productName = product.name
          item.productCode = product.barcode
          // 获取系统库存数量
          if (recheckForm.warehouseId) {
            try {
              const stockQuantity = await getProductStockQuantity(productId, recheckForm.warehouseId)
              item.systemQuantity = Number(stockQuantity) || 0
              console.log('获取到库存数量:', stockQuantity, '商品ID:', productId, '仓库ID:', recheckForm.warehouseId)
            } catch (error) {
              console.error('获取库存数量失败:', error)
              item.systemQuantity = 0
            }
          } else {
            item.systemQuantity = 0
          }
        }
      }
      calculateDifference(item)
    }

    const onWarehouseChange = () => {
      console.log('仓库改变:', recheckForm.warehouseId)
      // 当仓库改变时，重新获取所有商品的系统库存数量
      if (Array.isArray(recheckForm.items)) {
        recheckForm.items.forEach(item => {
          if (item && item.productId && recheckForm.warehouseId) {
            onProductChange(item, item.productId)
          } else if (item && item.productId) {
            // 如果还没有选择仓库，清空系统数量
            item.systemQuantity = 0
            calculateDifference(item)
          }
        })
      }
    }

    const calculateDifference = (item) => {
      if (!item) return
      
      const systemQty = Number(item.systemQuantity) || 0
      const actualQty = Number(item.actualQuantity) || 0
      item.difference = Math.round(actualQty - systemQty)
      console.log('计算差异:', { systemQty, actualQty, difference: item.difference })
    }

    const getDifferenceColor = (difference) => {
      if (difference === null || difference === undefined) return 'black'
      const numDiff = Number(difference)
      if (isNaN(numDiff)) return 'black'
      if (numDiff > 0) return 'green'
      if (numDiff < 0) return 'red'
      return 'black'
    }

    const resetRecheckForm = () => {
      Object.assign(recheckForm, {
        id: null,
        recheckNo: '',
        warehouseId: null,
        recheckDate: '',
        remark: '',
        items: [],
        status: 0
      })
      // 确保items是数组
      if (!Array.isArray(recheckForm.items)) {
        recheckForm.items = []
      }
    }

    const handleDialogClose = () => {
      dialogVisible.value = false
      resetRecheckForm()
    }

    const handleDetailDialogClose = () => {
      detailDialogVisible.value = false
      currentRecheck.value = {}
    }

    const submitForm = async () => {
      try {
        if (recheckForm.items.length === 0) {
          ElMessage.warning('请至少添加一个商品')
          return
        }

        if (isEdit.value) {
          await updateInventoryRecheck(recheckForm)
          ElMessage.success('更新成功')
        } else {
          await createInventoryRecheck(recheckForm)
          ElMessage.success('创建成功')
        }
        
        dialogVisible.value = false
        loadData()
      } catch (error) {
        console.error('提交失败:', error)
        ElMessage.error('提交失败')
      }
    }

    // 加载列表
    const loadData = async () => {
      loading.value = true
      try {
        const params = {
          pageNum: pagination.pageNum,
          pageSize: pagination.pageSize,
          recheckNo: searchForm.recheckNo,
          warehouseId: searchForm.warehouseId,
          startDate: searchForm.startDate,
          endDate: searchForm.endDate
        }
        const page = await getInventoryRecheckPage(params)
        console.log('复盘单数据:', page) // 添加调试日志
        tableData.value = Array.isArray(page?.records) ? page.records : []
        pagination.total = Number(page?.total) || tableData.value.length || 0
      } catch (error) {
        console.error('加载数据失败:', error)
        ElMessage.error('加载数据失败')
      } finally {
        loading.value = false
      }
    }

    onMounted(() => {
      loadData()
      loadWarehouseList()
      loadProductList()
    })

    return {
      // 数据
      loading,
      searchForm,
      pagination,
      tableData,
      warehouseList,
      productList,
      dialogVisible,
      detailDialogVisible,
      auditDialogVisible,
      voidDialogVisible,
      isEdit,
      dialogTitle,
      currentRecheck,
      recheckForm,
      formRules,
      // 方法
      handleSearch,
      resetSearch,
      handleSizeChange,
      handleCurrentChange,
      showAddDialog,
      showEditDialog,
      viewRecheckDetails,
      onAuditRecheck,
      onVoidRecheck,
      onDeleteRecheck,
      confirmAudit,
      confirmVoid,
      addProductItem,
      removeProductItem,
      onProductChange,
      onWarehouseChange,
      calculateDifference,
      getDifferenceColor,
      handleDialogClose,
      handleDetailDialogClose,
      submitForm,
      formatDateYMD
    }
  }
}
</script>

<style scoped>
.check-recheck-container {
  padding: 20px;
}

.search-bar {
  padding: 20px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.search-bar .el-input,
.search-bar .el-select,
.search-bar .el-date-picker {
  margin-right: 15px;
}

.search-bar .el-button {
  margin-left: 15px;
}

.items-container {
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 15px;
}

.items-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 10px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.recheck-detail .detail-header p { margin: 8px 0; }
.label { font-weight: bold; display: inline-block; width: 100px; }
</style>
